package member

import "encoding/json"

// 用户中心需要处理的消息类型
type handler interface {
	handle(w *reception, msg *Message) error
}

var memberRouter = map[string]handler{}

// 处理退出登录消息
type logoutController struct{}

func (h *logoutController) handle(w *reception, msg *Message) error {
	clients := w.account.findClients()
	clients.RemoveClient(w.client.Session, w.client.DevType)
	w.logout("ok")
	return nil
}

func init() {
	memberRouter[msgPathLogout] = &logoutController{}
}

// APNS 推送推送Token上传
type apnsController struct{}

type apnsInfo struct {
	Topic   string `json:"topic"`
	APNS    string `json:"apns"`
	DevType string `json:"dev_t"`
}

func (apns *apnsController) handle(w *reception, msg *Message) error {
	var a apnsInfo
	err := json.Unmarshal(msg.Data, &a)
	if err != nil {
		return err
	}

	clients := w.account.findClients()
	for _, client := range clients.Clients {
		if client.Session == w.client.Session && client.APNS != a.APNS {
			client.APNS = a.APNS
			clients.Save()
			break
		}
	}

	clients.Save()
	result := &Message{
		Path:   msg.Path,
		Method: msg.Method,
		State:  "ok",
	}
	return w.writeMessage(result)
}

func init() {
	memberRouter[msgPathMemberAPNS] = &apnsController{}
}
